<template>
    
    <el-card>
      <el-space style="width: 100%; justify-content: flex-end">
        <el-space>
            <el-button type="primary" @click="updateZbdw(true, {})">新增</el-button>
        </el-space>
    </el-space>
    </el-card>
    <el-table
      v-loading="state.oneDataListLoading"
      :data="state.oneTableData"
      stripe
      border
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="55" header-align="center" align="center"/>
      <el-table-column prop="editorUnitName" label="主编单位名称" header-align="center" align="center"/>
      <el-table-column prop="" label="操作" width="150" header-align="center" align="center">
        <template #default="scope">
          <el-icon :size="16" color="#1491FF" title="编辑" style="cursor: pointer; margin: 0 6px" @click="updateZbdw(false, scope.row)">
						<Edit />
					</el-icon>
          <el-icon :size="16" color="#fe6360" title="删除" style="cursor: pointer; margin: 0 6px" @click="deleitem(scope.row.id)">
						<Delete />
					</el-icon>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding-bottom: 15px;">
      <el-pagination :current-page="state.onePageNum" :page-sizes="state.onePageSizes" :page-size="state.onePageSize"
        :total="state.oneTotal" layout="total, sizes, prev, pager, next, jumper" @size-change="oneSizeChangeHandle"
        @current-change="oneCurrentChangeHandle">
      </el-pagination>
    </div>
    

    <!-- <el-card>
      <el-space style="width: 100%; justify-content: flex-end">
        <el-space>
            <el-button type="primary" @click="updateCbdw(true, {})">新增</el-button>
        </el-space>
    </el-space>
    </el-card>
    <el-table
      :data="state.twoTableData"
      stripe
      border
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="55" header-align="center" align="center"/>
      <el-table-column prop="name" label="参编单位名称" header-align="center" align="center"/>
      <el-table-column prop="" label="操作" width="150" header-align="center" align="center">
        <template #default="scope">
          <el-icon :size="16" color="#1491FF" title="编辑" style="cursor: pointer; margin: 0 6px" @click="updateCbdw(false, scope.row)">
						<Edit />
					</el-icon>
          <el-icon :size="16" color="#fe6360" title="删除" style="cursor: pointer; margin: 0 6px" @click="deleitemcb(scope.row.id)">
						<Delete />
					</el-icon>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding-bottom: 15px;">
      <el-pagination :current-page="state.twoPageNum" :page-sizes="state.twoPageSizes" :page-size="state.twoPageSize"
        :total="state.twoTotal" layout="total, sizes, prev, pager, next, jumper" @size-change="twoSizeChangeHandle"
        @current-change="twoCurrentChangeHandle">
      </el-pagination>
    </div> -->
  
    <cmDialog
      v-model="dialogOneVisible"
      :modal-title="state.titleFlag" 
      :before-close="addOrdelCancel"
      model-width="30%"
    >
      <el-form :model="state.oneForm" ref="zbdwFormRef" :rules="rules">
        <el-form-item label="次序" label-width="100px" prop="orderName">
          <el-input v-model="state.oneForm.orderName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="单位名称" label-width="100px" prop="editorUnitName">
          <el-input v-model="state.oneForm.editorUnitName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="联系人" label-width="100px" prop="contacts">
          <el-input v-model="state.oneForm.contacts" autocomplete="off" />
        </el-form-item>
        <el-form-item label="联系人电话" label-width="100px" prop="contactsTel">
          <el-input v-model="state.oneForm.contactsTel" autocomplete="off" />
        </el-form-item>
        <el-form-item label="联系人邮箱" label-width="100px" prop="contactsEmail">
          <el-input v-model="state.oneForm.contactsEmail" autocomplete="off" />
        </el-form-item>
        <el-form-item label="联系人地址" label-width="100px" prop="contactsAddress">
          <el-input v-model="state.oneForm.contactsAddress" autocomplete="off" />
        </el-form-item>
        <el-form-item label="负责人" label-width="100px" prop="responsiblePerson">
          <el-input v-model="state.oneForm.responsiblePerson" autocomplete="off" />
        </el-form-item>
        <el-form-item label="负责人电话" label-width="100px" prop="responsiblePersonTel">
          <el-input v-model="state.oneForm.responsiblePersonTel" autocomplete="off" />
        </el-form-item>
        <el-form-item label="负责人邮箱" label-width="100px" prop="responsiblePersonEmail">
          <el-input v-model="state.oneForm.responsiblePersonEmail" autocomplete="off" />
        </el-form-item>
        <el-form-item label="发布" label-width="100px" prop="isPublish">
          <el-radio-group v-model="state.oneForm.isPublish">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" label-width="100px">
          <el-input v-model="state.oneForm.remark" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-foot" style="padding-bottom: 20px;padding-right: 20px;">
          <el-button @click="addOrdelCancel">关闭</el-button>
          <el-button type="primary" @click="addOrdelSum(zbdwFormRef)">
            提交
          </el-button>
        </div>
      </template>
    </cmDialog>
  </template>
  
  <script lang="ts" setup>
  import { ref, reactive, computed, onMounted, watch, nextTick } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import cmDialog from '@/components/cm-dialog/index.vue'
  import type { FormInstance, FormRules } from 'element-plus'

  import {  editorUnitListApi, editorUnitUpdateApi, editorUnitDelApi } from '@/api/standard/maintenance/index'

  const state = reactive({
    oneTableData: [],
    oneDataListLoading: false,
    twoTableData: [{
      date: '2016-05-03',
      name: 'Tom',
      address: 'No. 189, Grove St, Los Angeles',
    }],
    twoDataListLoading: false,
    
    onePageNum: 1,
    onePageSize: 10,
    oneTotal: 1,
    onePageSizes: [10, 20],
    twoPageNum: 1,
    twoPageSize: 10,
    twoTotal: 1,
    twoPageSizes: [10, 20],

    oneForm: {
      systemId: "",
      orderName: "",
      editorUnitName: "",
      contacts: "",
      contactsTel: "",
      contactsEmail: "",
      contactsAddress: "",
      responsiblePerson: "",
      responsiblePersonTel: "",
      responsiblePersonEmail: "",
      isPublish: "",
      remark: "",
    },
    titleFlag: "",
    isZbOrCbFlag: false // true 主编单位  false 参编单位
  })
  const props = defineProps({
    // systemId: { 
    //   type: String,
    //   default: ''
    // },
    datainfo: { // 编制申报传递参数id、列表编辑id  对象
      type: Object,
      default: () => ({})
    }
  })
  // 获取数据
  const initZbdw = async () => {
    state.oneForm.systemId = props.datainfo.id
    var params = {
      systemId: props.datainfo.id
    }
    state.oneDataListLoading = true
    await editorUnitListApi(params).then(res => {  // 主编单位list
      state.oneTableData = res.data.list
      state.oneDataListLoading = false
      state.onePageNum = res.data.pageNum
      state.onePageSize = res.data.pageSize
      state.oneTotal = res.data.total
      // console.log("主编单位：", state.oneTableData)
    })
  }

  const dialogOneVisible = ref(false)
  // 表单验证
  const mobileRegExp = /^1[3456789]\d{9}$/
  const telValidator = (rule, value, callback) => {
      if (mobileRegExp.test(value)) {
      callback()
    } else {
      callback(new Error('手机号格式不正确'))
    }
  };
  interface RuleForm {
    id: string | Number,
    systemId: string | Number,
    orderName: string,
    editorUnitName: string,
    contacts: string,
    contactsTel: string,
    contactsEmail: string,
    contactsAddress: string,
    responsiblePerson: string,
    responsiblePersonTel: string,
    responsiblePersonEmail: string,
    isPublish: string | Number,
    remark: string,
  }
  const zbdwFormRef = ref<FormInstance>()
  const rules = reactive<FormRules<RuleForm>>({
    orderName: [{ required: true, message: '请输入次序', trigger: 'blur' }],
    editorUnitName: [{ required: true, message: '请输入单位名称',trigger: ['blur', 'change'] }],
    contacts: {required: true, message: '请输入联系人',trigger: ['blur', 'change']},
    contactsTel: [
      {required: true, message: '请输入联系人电话',trigger: ['blur', 'change']},
      { validator: telValidator, trigger: ['blur', 'change'] }
    ],
    contactsEmail: {type: 'email', required: true, message: '请输入联系人邮箱',trigger: ['blur', 'change']},
    contactsAddress: {required: true, message: '请输入联系人地址',trigger: ['blur', 'change']},
    responsiblePerson: {required: true, message: '负责人',trigger: ['blur', 'change']},
    responsiblePersonTel: [
      {required: true, message: '负责人电话',trigger: ['blur', 'change']},
      { validator: telValidator, trigger: ['blur', 'change'] }
    ],
    responsiblePersonEmail: {type: 'email', required: true, message: '负责人邮箱',trigger: ['blur', 'change']},
    isPublish: {required: true, message: '请选择是否发布',trigger: ['blur', 'change']},
  })

  const updateZbdw = (isUpdate: Boolean, row: any) => {
    state.isZbOrCbFlag = true
    state.titleFlag = isUpdate ? "新增主编单位" : "编辑主编单位"
    if(!isUpdate) {
      state.oneForm = {...row}
    }
    dialogOneVisible.value = true
  }

  const deleitem = (id: String|Number) => {
    	ElMessageBox.confirm('确定要删除吗？', '删除', {
    		confirmButtonText: '确定',
    		cancelButtonText: '取消',
    		type: 'warning'
    	}).then(() => {
        delMethods(id)
    	})
  }
  const delMethods = async (id: Number|String) => {
    var params = {
      id: id
    }
    await editorUnitDelApi(params).then(res => {  // 主编单位list
      ElMessage.success({
        message: '操作成功',
        duration: 500,
      })
      addOrdelCancel()
    })
  }
  const oneSizeChangeHandle = () => { }
  const oneCurrentChangeHandle = () => { }
  // 参编单位
  const updateCbdw = (isUpdate: Boolean, row: any) => {
    state.isZbOrCbFlag = false
    state.titleFlag = isUpdate ? "新增" : "编辑"
    dialogOneVisible.value = true
  }
  const deleitemcb = (id: String|Number) => {
    	ElMessageBox.confirm('确定要删除吗？', '删除', {
    		confirmButtonText: '确定',
    		cancelButtonText: '取消',
    		type: 'warning'
    	}).then(() => {
        
    	})
  }
  const twoSizeChangeHandle = () => { }
  const twoCurrentChangeHandle = () => { }
  // 提交数据0 主编单位; 1 参编单位
  const addOrdelSum = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        if(state.isZbOrCbFlag) {
          // 主编单位提交
          submitone(0)
        } else {
          // 参编单位
          submitone(1)
        }
      } else {
        console.log('提交错误', fields)
      }
    })
  }

  const submitone = async (type: any) => {
    await editorUnitUpdateApi(type, state.oneForm).then(res => {  // 主编单位list
        ElMessage.success({
            message: '操作成功',
            duration: 500,
        })
        addOrdelCancel()
    })
  }
  // 弹框取消
  const addOrdelCancel = () =>{
    dialogOneVisible.value = false
    zbdwFormRef.value?.resetFields(); // 表单验证关闭
    state.oneForm = { // 重置
      systemId: "",
      orderName: "",
      editorUnitName: "",
      contacts: "",
      contactsTel: "",
      contactsEmail: "",
      contactsAddress: "",
      responsiblePerson: "",
      responsiblePersonTel: "",
      responsiblePersonEmail: "",
      isPublish: "",
      remark: "",
    }
    initZbdw()
  }

  defineExpose({
    initZbdw,
  })
  </script>
  